<template>
	<view class="wallet-container">
		<u-navbar
			title="我的钱包"
			:autoBack="true"
			bgColor="#2883F8"
			leftIconColor="#fff"
			:titleStyle="{fontWeight: 700, color: '#fff'}"
			:rightText="getPlatform() === 'app' ? '退款记录' : ''"
		>
			<!-- 只在App端显示右侧按钮 -->
			<text v-if="getPlatform() === 'app'" slot="right" class="right-text" @click="rightClick">退款记录</text>
		</u-navbar>

		<view class="topHeader">
			<!-- 顶部信息 -->
			<view class="header" v-if="wallet">
				<view class="money-view" :style="{ width: isFleetUser ? '50%' : '33.333%' }">
					<view class="total-amount">{{ (wallet.balance / 100).toFixed(2) || 0.00 }}</view>
					<view class="amount-label">总金额</view>
				</view>
				<view class="divider"></view>
				<view class="money-view" :style="{ width: isFleetUser ? '50%' : '33.333%' }" v-if="!isFleetUser">
					<view class="total-amount">{{ (wallet.balance / 100).toFixed(2) || 0.00 }}</view>
					<view class="amount-label">可退金额</view>
				</view>
				<view class="divider"></view>
				<view class="money-view" :style="{ width: isFleetUser ? '50%' : '33.333%' }" v-if="!isFleetUser">
				    <view>
				        <text class="total-amount">{{ (wallet.fleetBalance / 100).toFixed(2) || 0.00 }}</text>
				    </view>
				    <text class="amount-label">车队余额</text>
				</view>
				
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons" v-if="!isFleetUser">
				<view @click="recharge" class="btn recharge-btn">充值</view>
				<view type="error" @click="withdraw" class="btn withdraw-btn">退款</view>
				<!-- 非App端添加退款记录入口 -->
				<view v-if="getPlatform() != 'app'" @click="rightClick" class="btn record-btn">退款记录</view>
			</view>
		</view>

		<!-- 使用记录 -->
		<view class="record-section">
			<text class="record-title">使用记录</text>
			<view class="date-range" @click="openDateRange">
				<view class="date-input">{{ startDate }}</view>
				<view class="date-separator">~</view>
				<view class="date-input">{{ endDate }}</view>
			</view>
			<view class="date-tip">选择任意时间区间查询记录</view>
			<view class="record-total">
				<view>充值: ¥ {{ Math.abs(rechargeTotal || 0) }}</view>
				<view>退款: ¥ {{ Math.abs(withdrawTotal || 0) }}</view>
				<view>支出: ¥ {{ Math.abs(consumeTotal || 0) }}</view>
			</view>
			<view class="record-list"> 
				<view class="record-item" v-for="(record, index) in list" :key="index">
					<view class="left-area">
						<view class="record-item-type">{{ record.title }}</view>
						<!-- <view class="record-item-desc">描述</view> -->
						<view class="record-item-date">{{ formatTime(record.createTime) }}</view>
					</view>
					<view class="right-area">
						<view class="money">{{ (record.price / 100).toFixed(2) || 0.00 }}</view>
					</view>
				</view>
			</view>
		
			<!-- 空状态 -->
			<view class="empty" v-if="list && list.length == 0"><u-empty mode="data"></u-empty></view>
		</view>
		
		<u-calendar 
			:show="show" 
			:mode="mode" 
			:insert="true"
			:minDate="'2025-01-01'"
			:maxDate="'2035-01-01'"
			:monthNum="12"
			@confirm="confirm" 
			@close="openDateRange"
		></u-calendar>
	</view>
</template>

<script>
	import { mapState} from 'vuex'
	import { getIsFleetUser } from '@/common/cacheManager.js';
	export default {
		data() {
			// 获取当前日期
			const getCurrentDate = (offset = 0) => {
				const date = new Date();
				date.setDate(date.getDate() - offset); // 添加偏移天数参数
				return date.toISOString().split('T')[0];
			};
			
			return {
				show: false,
				mode: 'range',
				startDate: getCurrentDate(7),  // 默认显示前一周
				endDate: getCurrentDate(),      // 默认当天
				rechargeTotal: 0.00,
				withdrawTotal: 0.00,
				consumeTotal: 0.00,
				list: [],
				wallet: {
					balance: 0,
					freezePrice: 0,
					freezePriceChedui: 0,
					fleetBalance: 0
				},
				
				formData: {
					pageNo: 1,
					pageSize: 10,
					type: 0
				},
				
				walletForm: {
					createTime: [
						`${getCurrentDate(7)}T00:00:00`,  // 一周前开始时间
						`${getCurrentDate()}T23:59:59`     // 当天结束时间
					],
					times: ''
				},
				isFleetUser: false,
			}
		},
		computed: {
			//引入store全局变量
			...mapState(['loginState', 'userInfo'])
		},
		onLoad() {
			this.getWalletInfo();
		},
		onShow() {
			
			if (this.loginState) {
				this.getWalletInfo();
				this.fetchIsFleetUserStatus();
			} else {
				this.resetState();
			}
			
		},
		methods: {
			
			// 重置状态
			resetState() {
				
				this.wallet = {
					balance: 0,
					freezePrice: 0,
					freezePriceChedui: 0,
					fleetBalance: 0
				};
				
			},
			
			// 新增一个方法来获取并设置 isFleetUser 状态
			async fetchIsFleetUserStatus() {
			    try {
			        const status = await getIsFleetUser(); // 调用缓存管理器中的函数
			        this.isFleetUser = status; // 将结果存入 data
			    } catch (error) {
			         // 处理错误，例如网络问题或 API 错误
			         console.error('获取 isFleetUser 状态失败:', error);
			         // 可以选择性地设置一个默认值，或者显示错误提示
			         // 为了安全起见，如果获取失败，可以默认隐藏（即设为 true），或者显示（设为 false）
			         // 这里我们假设获取失败时默认显示冻结金额（更保守）
			         this.isFleetUser = false;
			         // 或者显示用户友好的提示
			         // uni.showToast({ title: '获取用户状态失败', icon: 'none' });
			    }
			},
			// 获取用户钱包信息
			getWalletInfo() {
				this.$http_api.userWallet({}).then((res) => {
					this.wallet = res;
					this.getWalletSummary();
					this.getRechargeLog();
				})
			},
			// 获取钱包统计
			getWalletSummary() {
				const params = {
					startTime: this.walletForm.createTime[0].replace(' ', 'T'),
					endtTime: this.walletForm.createTime[1].replace(' ', 'T')
				};
				this.$http_api.userWalletSummary(params).then(res => {
					this.rechargeTotal = (res.totalIncome / 100).toFixed(2) || 0.00;
					this.withdrawTotal = (res.withdraw / 100).toFixed(2) || 0.00;
					this.consumeTotal = (res.totalExpense / 100).toFixed(2) || 0.00;
				})
			},
			// 获取充值记录
			getRechargeLog() {
				this.$http_api.userWalletLog({
					...this.formData,
					startTime: this.walletForm.createTime[0].replace(' ', 'T'),
					endtTime: this.walletForm.createTime[1].replace(' ', 'T')
				}).then(res => {
					this.list = res.list
				})
			},
			rightClick() {
				uni.navigateTo({
					url: '/pages/user/wallet/withdraw-log'
				})
			},
			recharge() {
				// 充值逻辑
				uni.navigateTo({
					url: '/pages/user/wallet/recharge'
				})
			},
			withdraw() {
				// 退款逻辑
				uni.navigateTo({
					url: '/pages/user/wallet/withdraw'
				})
			},
			confirm(e) {
				this.startDate = e[0];
				this.endDate = e[e.length - 1];
				// 更新查询参数
				this.walletForm.createTime = [
					`${this.startDate}T00:00:00`,
					`${this.endDate}T23:59:59`
				];
				this.show = false;
				// 触发接口调用
				this.getWalletSummary();
				this.getRechargeLog();
			},
			openDateRange(e) {
				uni.showLoading({ title: '加载中....' })
				this.show = !this.show;
				setTimeout(() => uni.hideLoading(), 300)
			},
			// 获取格式化后的当前日期
			getFormattedDate(date = new Date()) {
				return date.toISOString().split('T')[0];
			},
			
			formatTime(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			// 获取当前平台
			getPlatform() {
				// #ifdef APP-PLUS
				return 'app';
				// #endif
				
				// #ifdef MP-WEIXIN
				return 'mp-weixin';
				// #endif
				
				// #ifdef H5
				return 'h5';
				// #endif
				
				return 'other';
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wallet-container {
		min-height: 100vh;
		background-color: #ffffff;
		
		.right-text {
			color: #fff;
			font-size: 30rpx;
		}

		.topHeader {
			// height: 350rpx;
			background: #2883F8;
			padding: 0 45rpx 30rpx 45rpx;
			font-size: 44rpx;
			padding-top: calc(180rpx + var(--window-top));

			.header {
				height: 160rpx;
				padding: 20rpx 10rpx;
				color: white;
				font-weight: bold;
				display: flex;
				justify-content: space-between;

				.divider {
					margin-top: 40rpx;
					width: 1rpx;
					height: 49rpx;
					background-color: #ffffffff;
				}

				.money-view {
					text-align: center;

					.amount-label {
						font-size: 31rpx;
						font-weight: 400;
						margin-top: 10rpx;
					}
				}
			}

			.action-buttons {
				display: flex;
				justify-content: center;
				flex-wrap: nowrap; 
				
				.btn {
					flex: 1;
					min-width: 180rpx;
					max-width: 210rpx;
					text-align: center;
					font-weight: 400;
					font-size: 28rpx;
					color: #FFFFFF;
					line-height: 80rpx;
					height: 80rpx;
					background-color: #42E0A2;
					border-radius: 60rpx;
					margin-bottom: 20rpx;
					
					&.withdraw-btn {
						background-color: #FE6601;
					}
					
					&.record-btn {
						background-color: #000000;
					}
					
					&:nth-child(2) {
						margin: 0 20rpx;
					}
				}
			}
		}

		.record-section {
			position: relative;
			top: -10rpx;
			left: 0;
			background-color: #ffffffff;
			border-radius: 24rpx;
			padding: 50rpx 40rpx;

			&::after {
				content: '';
				position: absolute;
				top: -1rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 0;
				height: 0;
				border-left: 35rpx solid transparent;
				border-right: 35rpx solid transparent;
				border-top: 25rpx solid #2883F8;
			}

			.record-title {
				font-weight: 600;
				font-size: 31rpx;
				color: #333333;
			}

			.date-range {
				display: flex;
				justify-content: center;
				margin-top: 20rpx;

				.date-input {
					height: 74rpx;
					background: #FFFFFF;
					border-radius: 7rpx 7rpx 7rpx 7rpx;
					border: 1rpx solid #707070;
					width: 300rpx;
					line-height: 74rpx;
					text-align: center;
					font-weight: 400;
					font-size: 31rpx;
					color: #333333;
					font-style: normal;
				}

				.date-separator {
					height: 74rpx;
					line-height: 74rpx;
					width: 50rpx;
					text-align: center;
				}
			}

			.date-tip {
				text-align: center;
				font-size: 24rpx;
				color: #999;
				margin-top: 10rpx;
				margin-bottom: 15rpx;
			}

			.record-total {
				display: flex;
				font-size: 26rpx;
				color: #777777;
				font-weight: 400;
				gap: 40rpx;
				padding: 20rpx 10rpx;
			}

			.record-list {
				.record-item {
					display: flex;
					justify-content: space-between;
					margin: 10rpx;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #eeeeee;

					.left-area {
						.record-item-type {
							font-size: 30rpx;
							color: #42E0A2;
							font-weight: 600;
							padding: 10rpx 0;

							&.withdraw {
								color: #FE6601
							}

							&.consume {
								color: #1C6EFB;
							}
						}

						.record-item-desc {
							color: #333333;
							font-weight: 400;
							font-size: 24rpx;
						}

						.record-item-date {
							color: #777777;
							font-size: 24rpx;
							font-weight: 400;
							margin-top: 10rpx;
						}
					}

					.right-area {
						.money {
							color: #42E0A2;
							margin-top: 30rpx;
							font-size: 35rpx;
							font-weight: 400;

							&.withdraw {
								color: #FE6601
							}

							&.consume {
								color: #1C6EFB;
							}
						}
					}
				}
			}
		}
	}
</style>